package org.spring.userservice.Util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @auther loongs
 * @date 2017/11/22  16:53
 */
@Component
public class RedisUtil {
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 判断缓存中是否有对应的value
     * @param key
     * @return
     */
    @SuppressWarnings("unchecked")
    public boolean exists(final String key){
        return redisTemplate.hasKey(key);
    }

    /**
     * 删除对应的value
     * @param key
     */
    @SuppressWarnings("unchecked")
    public void remove(final String key){
        if(exists(key)){
            redisTemplate.delete(key);
        }
    }

    /**
     * 批量删除对应的value
     * @param keys
     */
    @SuppressWarnings("unchecked")
    public void remove(final String... keys){
        for (String key:keys) {
            remove(key);
        }
    }

    /**
     * 批量删除匹配到key的value
     * @param pattern
     */
    @SuppressWarnings("unchecked")
    public void removePattern(final String pattern){
        Set<Serializable> keys = redisTemplate.keys(pattern);
        if(keys.size()>0){
            redisTemplate.delete(keys);
        }
    }
    /**
     * 写入缓存redis
     * @param key
     * @param value
     * @return
     */
    @SuppressWarnings("unchecked")
    public boolean set(final String key, Object value){
        boolean result=false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key,value);
            result=true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 写入缓存redis
     * @param key
     * @param value
     * @param expireTime 过期时长，单位为秒
     * @return
     */
    @SuppressWarnings("unchecked")
    public boolean set(final String key, Object value,Long expireTime){
        boolean result=false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key,value);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result=true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 读取缓存redis
     * @param key
     * @return
     */
    @SuppressWarnings("unchecked")
    public Object get(final String key){
        Object result=null;
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        result=operations.get(key);
        return result;
    }


}
